package com.duowei.diandan.fragment.dialog;

import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.TasteRequiredAdapter;
import com.duowei.diandan.bean.food.Taste;
import com.duowei.diandan.databinding.TasteDialogFragmentBinding;
import com.duowei.diandan.db.entry.Dmpzsd;
import com.duowei.diandan.db.entry.Tcsd;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.viewmodel.TasteViewModel;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 口味窗口
 */
public class TasteDialogFragment extends BaseDialogFragment implements View.OnClickListener {

    private TasteDialogFragmentBinding mBinding;

    private static int mType = 1;

    // 1
    private long mWmlsbId;
    private Wmlsb mWmlsb;

    // 2
    private Tcsd mTcsd;

    private ArrayList<Taste> mTasteList;
    private TasteRequiredAdapter mTasteRequiredAdapter;

    public static TasteDialogFragment newInstance(long wmlsbId) {

        Bundle args = new Bundle();
        args.putInt("type", 1);
        args.putLong("wmlsb_id", wmlsbId);

        TasteDialogFragment fragment = new TasteDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static TasteDialogFragment newInstance(Tcsd tcsd) {

        Bundle args = new Bundle();
        args.putInt("type", 2);
        args.putSerializable("tcsd", tcsd);

        TasteDialogFragment fragment = new TasteDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mType = getArguments().getInt("type");
            if (mType == 1) {
                mWmlsbId = getArguments().getLong("wmlsb_id");

            } else if (mType == 2) {
                //noinspection unchecked
                mTcsd = (Tcsd) getArguments().getSerializable("tcsd");
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_taste_dialog, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext(), FlexDirection.ROW, FlexWrap.WRAP);
        mBinding.tasteRecyclerView.setLayoutManager(layoutManager);

        mBinding.btnCancel.setOnClickListener(this);
        mBinding.btnConfirm.setOnClickListener(this);

        if (mType == 1) {
            mBinding.titleView.setText("口味选择");
            if (mWmlsbId > 0) {
                mWmlsb = getDb().wmlsbDao().findOneById(mWmlsbId);

                if (mWmlsb != null) {
                    TasteViewModel viewModel = ViewModelProviders.of(this).get(TasteViewModel.class);
                    viewModel.getLiveData(mWmlsb.getXmbh()).observe(this, dmpzsds -> {

                        if (dmpzsds != null) {
                            if (dmpzsds.size() == 0) {
                                // 当未发现对应口味时,显示所以口味
                                dmpzsds = getDb().dmpzsdDao().findAll();
                                if (dmpzsds.size() == 0) {
                                    // 所以口味都没有时,关闭窗口
                                    Toast.makeText(getContext(), "没有口味信息", Toast.LENGTH_SHORT).show();
                                    dismiss();
                                } else {
                                    handleData(dmpzsds);
                                }

                            } else {
                                handleData(dmpzsds);
                            }
                        }
                    });
                }
            }
        } else if (mType == 2) {
            mBinding.titleView.setText(String.format(Locale.CHINA, "%s 口味选择", mTcsd.getXmmc1()));
            mTasteRequiredAdapter = new TasteRequiredAdapter(mTcsd.getTasteList());
            mBinding.tasteRecyclerView.setAdapter(mTasteRequiredAdapter);
        }
    }

    private void handleData(List<Dmpzsd> dmpzsds) {
        mTasteList = new ArrayList<>();
        for (Dmpzsd d : dmpzsds) {
            mTasteList.add(new Taste(d));
        }

        mTasteRequiredAdapter = new TasteRequiredAdapter(mTasteList);
        mBinding.tasteRecyclerView.setAdapter(mTasteRequiredAdapter);

        loadTasteToList();
    }

    /**
     * 从购物车数据库载入已经保存的口味
     */
    private void loadTasteToList() {
        if (mWmlsb != null && !TextUtils.isEmpty(mWmlsb.getPz())) {
            String pzString = mWmlsb.getPz();

            Pattern pattern = Pattern.compile("\\((.*?)\\)");
            Matcher matcher = pattern.matcher(pzString);

            while (matcher.find()) {
                String s = matcher.group(1);

                if (mTasteList != null && !TextUtils.isEmpty(s)) {
                    for (Taste t : mTasteList) {
                        if (s.equals(t.getDmpzsd().getNr())) {
                            t.setChecked(true);
                        }
                    }
                }
            }
        }
    }

    /**
     * 保存选择的口味到购物车数据库
     */
    private void saveTasteToCart() {
        if (mWmlsb != null && mTasteRequiredAdapter != null) {
            mWmlsb.setPz(mTasteRequiredAdapter.getCheckedString());
            getDb().wmlsbDao().update(mWmlsb);
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_cancel) {
            dismiss();
        } else if (view.getId() == R.id.btn_confirm) {
            if (mType == 1) {
                saveTasteToCart();
            }

            if (mOnClickListener != null) {
                mOnClickListener.onConfirmClick();
            }
            dismiss();
        }
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    private OnClickListener mOnClickListener;

    public interface OnClickListener {
        void onConfirmClick();
    }
}
